//任务
const ws = require('ws');
const qs = require('qs');
const dayjs = require('dayjs');
const os = require("os");
const wsServer = new ws.Server({ port: 5003 });
//发送
wsServer.send = function (statusCode, type, data, message, ws) {
  jsonData = JSON.stringify({
    statusCode,
    type,
    data,
    message,
  });
  //console.log('发送', jsonData);
  ws.send(jsonData);
};
wsServer.on('connection', (ws, req) => {
  //let prarms = qs.parse(req.url.split('?')[1]);
  console.log('连接成功', {
    code: 1000,
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  ws.on('message', async (msg) => {
    let message = JSON.parse(msg);
    switch (message.type) {
      case 'PING':
        wsServer.send(1000, 'PONG', {}, '成功', ws);
        break;
      case 'MESSAGE':
        let memory = process.memoryUsage();
        let osTotalmem=(os.totalmem()/1024/1024).toFixed(2);//系统总内存
        let osFreemem=(os.freemem()/1024/1024).toFixed(2);//系统剩余内存
        wsServer.send(
          1000,
          'MESSAGE',
          {
            time: dayjs().format('YYYY-MM-DD hh:mm:ss'),
            rss:(memory.rss/1024/1024).toFixed(2),
            external:(memory.external/1024/1024).toFixed(2),
            heapTotal: (memory.heapTotal / 1024 / 1024).toFixed(2),
            heapUsed: (memory.heapUsed / 1024 / 1024).toFixed(2),
            osTotalmem: osTotalmem,
            osUseFreemem:osTotalmem-osFreemem
          },
          '成功',
          ws
        );
        break;
      default:
        wsServer.send(1001, 'ERROR', {}, '错误', ws);
        break;
    }
  });
  ws.on('close', async (code) => {
    console.log('关闭连接', {
      code,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    });
  });
  ws.on('error', (code) => {
    console.log('异常', {
      code,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    });
  });
});
